<template>
  <xn-form-container
    :title="formData.RoleName + '-权限授权'"
    :width="800"
    :visible="visible"
    :destroy-on-close="true"
    @close="onClose"
  >
    <a-table
      childrenColumnName="Childs"
      ref="tableRef"
      :columns="columns"
      :data-source="data"
      :alert="options.alert.show"
      bordered
      :row-key="(record) => record.ID"
      :tool-config="toolConfig"
      :row-selection="options.rowSelection"
      :pagination="false"
      :indentSize="30"
      :scroll="{ x: 'max-content' }"
      :expandedRowKeys="expandedRowKeys"
      @expand="expand"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <div v-if="record.PModuleID === 0">
            <a-checkbox
              v-model:checked="record.RolePower[0]"
              @change="modifyPower(record.ID, record.RolePower)"
              >查看</a-checkbox
            >
          </div>
          <div v-else>
            <template v-for="(item, index) in record.RolePower" :key="index">
              <a-checkbox
                v-model:checked="record.RolePower[index]"
                @change="changeCheckbox(index, record.RolePower[index], record)"
              >
                <template v-if="index === 0">查看</template>
                <template v-else-if="index === 1">新增</template>
                <template v-else-if="index === 2">修改</template>
                <template v-else-if="index === 3">删除</template>
              </a-checkbox>
            </template>
          </div>
        </template>
      </template>
    </a-table>
    <template #footer>
      <a-button class="xn-mr8 mr10" @click="onClose">关闭</a-button>
      <a-button type="primary" @click="onSubmit">保存</a-button>
    </template>
  </xn-form-container>
</template>

<script setup>
import rolemgrApi from "@/api/systemManagement/rolemgrApi";
import { ref, onMounted, watch } from "vue";
import XnFormContainer from "@/components/XnFormContainer/index.vue";
import { message } from "ant-design-vue";
import { cloneDeep } from "lodash-es";

// 默认是关闭状态
const visible = ref(false);
const emit = defineEmits({ successful: null });

// 表单数据
const formData = ref({
  RoleDesp: "",
});
// 打开抽屉
const onOpen = (record) => {
  visible.value = true;
  if (record) {
    formData.value = Object.assign({}, record);
  } else {
    formData.value = {};
  }
};
// 关闭抽屉
const onClose = () => {
  visible.value = false;
};

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
  onOpen,
});

/* 表格配置 */
const tableRef = ref();
const columns = [
  /* {
    title: "层级",
    dataIndex: "PModuleID",
    align: "center",
  }, */
  {
    title: "模块名称",
    dataIndex: "ModuleName",
    align: "left",
    width: "200px",
  },
  {
    title: "操作",
    dataIndex: "action",
    align: "center",
  },
];
// 列表选择配置
const options = {
  alert: {
    show: false,
    clear: () => {
      selectedRowKeys = ref([]);
    },
  },
};
const toolConfig = {
  refresh: false,
  height: false,
  columnSetting: false,
  striped: false,
};
// 展开行配置数组
let expandedRowKeys = ref([]);
const expand = (e, item) => {

  if (!e) {
    expandedRowKeys.value.splice(
      expandedRowKeys.value.findIndex((i) => i == item.ID),
      1
    );
  } else {
    expandedRowKeys.value.push(item.ID);

  }
};
// 进行数据转换,删掉空的子数组,不然会展示一个无法展开的展开按钮
const transformChilds = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].Childs.length > 0) {
      transformChilds(arr[i].Childs);
    } else {
      delete arr[i].Childs;
    }
  }
};
const transformRolePower = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    // 赋值
    let rolePower = arr[i].RolePower;
    // 转为二进制字符串,并补齐八位

    let _rolePower = rolePower.toString(2).padStart(8, 0);
    // 反转字符串,只取前四位，
    let flippedArr = _rolePower.split("").reverse().slice(0, 4);
    //转为布尔值数组赋值给RolePower字段
    let mapFilppedStr = flippedArr.map((i) => (i === "1" ? true : false));
    // 回来赋值给RolePower字段
    arr[i].RolePower = mapFilppedStr;
    // 递归子数组
    if (arr[i].Childs) {
      transformRolePower(arr[i].Childs);
    }
  }
};
let data = ref([]);
const loadData = () => {


  rolemgrApi
    .getRoleModulePower({
      RoleID: formData.value.ID,
    })
    .then((res) => {
      let Data = res.Data;
      transformChilds(Data);
      transformRolePower(Data);
      data.value = Data;
      for (let i = 0; i < data.value.length; i++) {
        if (data.value[i].ID) {
          expandedRowKeys.value.push(data.value[i].ID);
        }
      }
    });
};
// 监听是否打开了抽屉,如果是则请求数据,用来选择上级部门
watch(
  () => visible.value,
  (n, o) => {
    if (n) {
      // 重置数组,防止点开抽屉时,上次的展开状态还在

      expandedRowKeys.value=[];
      loadData();
    }
  }
);

// 菜单的选中查看选中之后全选
const changeCheckbox = (index, bool, record) => {
  let rolePowerArr = record.RolePower;
  let PModuleID = record.PModuleID;

  if (index === 0 && !bool) {
    let Childs;
    for (let i = 0; i < data.value.length; i++) {
      if (data.value[i].ModuleID == PModuleID) {
        Childs = data.value[i].Childs;
      }
    }
    for (let i = 0; i < Childs.length; i++) {
      if (Childs[i].ID == ID) {
        if (
          !Childs[i].RolePower[0] &&
          Childs[i].RolePower[1] &&
          Childs[i].RolePower[2] &&
          Childs[i].RolePower[3]
        ) {
          Childs[i].RolePower = [false, false, false, false];
          rolePowerArr = [false, false, false, false];
        }
      }
    }
  }
  modifyPower(record.ID, rolePowerArr);
};

const modifyPower = (ID, rolePowerArr) => {
  let _data = cloneDeep(rolePowerArr);
  let reverseData = _data.reverse();
  let mapData = reverseData.map((i) => (i ? 1 : 0)).join("");
  let Power = parseInt(mapData, 2);
  rolemgrApi
    .modifyRoleModulePower({
      ID,
      Power,
    })
    .then((res) => {
      if (!res.Result) {
        message.error("修改失败");
        return;
      }
      message.success("修改成功");
      loadData();
    })
    .catch(() => {
      message.success("修改失败");
    });
};

const onSubmit = () => {
  let _data = cloneDeep(data.value);
};
</script>
